package cc.vv.party.common.base

import cc.vv.party.beans.vo.*
import cc.vv.party.common.constants.StatusCode
import cc.vv.party.common.constants.SysConsts
import cc.vv.party.common.constants.enums.OrgType
import cc.vv.party.common.constants.enums.RoleType
import cc.vv.party.common.wrapper.ResponseEntityWrapper
import cc.vv.party.exception.BizException
import org.slf4j.LoggerFactory
import org.springframework.validation.annotation.Validated
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpSession

/**
 * @author chengyi
 */
@Validated
class BaseController {

    val logger by lazy { LoggerFactory.getLogger(BaseController::class.java) }

    /**
     * 成功响应
     */
    fun <T> success(t: T?): ResponseEntityWrapper<T> {
        return ResponseEntityWrapper.success(t)
    }

    /**
     * 错误响应
     */
    fun <T> error(statusCode: StatusCode): ResponseEntityWrapper<T> {
        return ResponseEntityWrapper.error(statusCode)
    }

    /**
     * 错误响应
     */
    fun <T> error(code: Int, message: String): ResponseEntityWrapper<T> {
        return ResponseEntityWrapper.error(code, message)
    }

    fun getSessionIfAbsent(): HttpSession {
        return getRequest().session
    }

    fun getSession(): HttpSession {
        return getRequest().getSession(false) ?: throw BizException(StatusCode.FORBIDDEN)
    }

    fun getRequest(): HttpServletRequest {
        return (RequestContextHolder.getRequestAttributes() as ServletRequestAttributes).request
    }

    fun getResponse(): HttpServletResponse? {
        return (RequestContextHolder.getRequestAttributes() as ServletRequestAttributes).response
    }

    fun getCurrentUserId(): String {
        val session = getSession()
        return session.getAttribute(SysConsts.SESSION_KEY_USER_ID).toString()
    }

    fun getCurrentUserName(): String {
        val session = getSession()
        return session.getAttribute(SysConsts.SESSION_KEY_USER_NAME).toString()
    }

    fun getCurrentUserAccount(): String {
        val session = getSession()
        return (session.getAttribute(SysConsts.SESSION_KEY_USER_ACCOUNT)
            ?: throw BizException(StatusCode.MESSAGE_NOT_EXIST.statusCode, "账号不存在")).toString()
    }

//    fun getCurrentUserOrg(): List<OrgVO> {
//        val session = getSession()
//        return session.getAttribute(SysConsts.SESSION_KEY_USER_ORG) as List<OrgVO>
//    }

    //    fun getCurrentUserOrgTree(): OrgVO {
//        val session = getSession()
//        return session.getAttribute(SysConsts.SESSION_KEY_USER_ORG_TREE) as OrgVO
//    }
//
    fun getCurrentUserRole(): List<RoleVO> {
        val session = getSession()
        return session.getAttribute(SysConsts.SESSION_KEY_USER_ROLE) as List<RoleVO>
    }
//
//    fun getAppUserOrgList(): List<OrgVO> {
//        val session = getSession()
//        return session.getAttribute(SysConsts.SESSION_KEY_APP_USER_ORG) as List<OrgVO>
//    }


    fun checkPartyAdmin() {
        val session = getSession()
        if (session.getAttribute(SysConsts.SESSION_KEY_YANAN_ROLE_ID) != "RCME"
            && session.getAttribute(SysConsts.SESSION_KEY_YANAN_ROLE_ID) != "PROME"
        ) {
            throw BizException(StatusCode.FORBIDDEN)
        }
    }

    fun getYananRole(): String {
        val session = getSession()
        return session.getAttribute(SysConsts.SESSION_KEY_YANAN_ROLE_ID).toString()
    }

    fun getCurrentUserInfo(): UserVO {
        val session = getSession()
        //获取用户报道信息
        var userVO = session.getAttribute(SysConsts.SESSION_KEY_LOCAL_USER_INFO) as? UserVO
        if (userVO == null) {
            userVO = UserVO()
            userVO.id = session.getAttribute(SysConsts.SESSION_KEY_USER_ID).toString()
            //获取管理员
            val adminOrgList = session.getAttribute(SysConsts.SESSION_KEY_ADMIN_ORG) as? List<OrgVO>
            if (adminOrgList != null) {
                val map = adminOrgList.associateBy { it.type }
                userVO.street = map[OrgType.STREET]?.id
                userVO.community = map[OrgType.SECTION]?.id
                userVO.grid = map[OrgType.GRID]?.id
                userVO.area = map[OrgType.AREA]?.id
            }
        }
        return userVO
    }

    /** 获取当前登录党员信息（仅适用于APP端） */
    fun getPartyInfo(): UserVO {
        val session = getSession()
        //获取用户报道信息
        return session.getAttribute(SysConsts.SESSION_KEY_LOCAL_USER_INFO) as? UserVO ?: throw BizException(StatusCode.MESSAGE_NOT_EXIST.statusCode, "当前用户未报到，请先进入报道")
    }

    fun getCurrentBranch(): CurrentBranchInfoVO {
        val session = getSession()
        var branch = session.getAttribute(SysConsts.SESSION_KEY_CURRENT_BRANCH) as? CurrentBranchInfoVO
        if (getCurrentUserAccount() == "admin") {
            branch = CurrentBranchInfoVO(
                "", "", "", "",
                "", "", "", "", "", ""
            )
        } else {
            if (branch == null) {
                throw BizException(
                    StatusCode.FORBIDDEN.statusCode,
                    "无操作权限"
                )
            }
        }
        return branch
    }

    //根据权限，获取当前用户所管理的组织机构
    fun getUserManageOrgInfo(): UserManageOrgInfoVO {
        val session = getSession()
        return session.getAttribute(SysConsts.SESSION_KEY_MANAGE_ORG_INFO) as UserManageOrgInfoVO
    }
}